package website.lucaswork.survey.mvc.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import website.lucaswork.survey.core.converters.StringToLocalDateTimeConverter;
import website.lucaswork.survey.core.entities.Survey;
import website.lucaswork.survey.core.entities.User;
import website.lucaswork.survey.mvc.forms.CreateSurveyForm;

import java.sql.Timestamp;

@Component
public class ConvertUtil {

    @Autowired
    FileUploader fileUploader;

    @Autowired
    StringToLocalDateTimeConverter converter;

    public Survey toSurveyValue(CreateSurveyForm form) throws Exception {
        Survey survey = new Survey();
        survey.setUser(getCurrentUser());
        survey.setBgUrl(fileUploader.upload(form.getBg()));
        survey.setCover(fileUploader.upload(form.getCover()));
        survey.setDescription(form.getDescription());
        survey.setDoneCount(0);
        survey.setEndTest(form.getEndText());
        survey.setEndTime(Timestamp.valueOf(converter.convert(form.getEndTime())));
        survey.setFrontTest(form.getFrontText());
        survey.setStartTime(Timestamp.valueOf(converter.convert(form.getStartTime())));
        survey.setTitle(form.getTitle());
        survey.setVisitCount(0);
        survey.setSlug(convertStringToSlug(form.getTitle()));
        return survey;
    }

    private User getCurrentUser() {
        return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    private String convertStringToSlug(String title) {
        StringBuilder sb = new StringBuilder();
        sb.append(title.replaceAll("[^a-zA-Z0-9\\s]", "").replace(" ", "_").toLowerCase())
                .append("_by_").append(getCurrentUser().getUsername().replaceAll("[^a-zA-Z0-9\\s]", "").replace(" ", "_"));
        return sb.toString();

    }
}
